require 'init'
require 'search'
require 'amatch'
require 'props_config'
=begin
	1. 逐条读取待匹配的记录
	2. 用该条记录进行搜索,查找候选集,搜索时,限定 -nick +brand +cat1,现暂只取前500条记录
	3. 比较候选集中的title相似度
	4. 筛选出结果,储入联盟表中
	5. 价格匹配比较
=end

#TODO 添加日志记录

module Match
	class Matcher
		include Amatch
		
		COUTER_ID = 2
		MAX_SORCE = 0.6
		MAX_SIMILAR = 0.75
		PROP_SORCE = 0.6
		STEP_LENGTH = 1000
		#SEARCH_STEP = 10
		
		def initialize
			@tao_db_help = DBHelp::DBHelp.create_tao_hidoudou
			@item_count = get_item_count()
			@prop_config = PropsConfig.load()
			@remarks = ""
			#puts @prop_config
			puts "item count : #{@item_count}" 
		end
		
		def analyzer
			#debugger
			0.upto(get_item_count() / STEP_LENGTH + 1) do |i|
				fetch_data.each_hash do |item|
					item_id = item["id"]
					source_title = item["format_title"]
					source_props = parse_props(item["props_str"])
					puts "source - id:#{item["id"]} title:#{source_title}"
				
					s = Search.new()
					s.query(source_title, item["cat1_id"], source_props["品牌"], item["nick"])
					puts "#{item_id}: #{s.total_hits} - #{s.results.size}" 
					#debugger
					#循环取搜索结果
					s.results.each do |r|
						repeat_item_id = r[:id]
						
						break if repeat_item_id.to_i == item_id.to_i
						
						break if r[:score] < MAX_SORCE
						@remarks = ""
						
						#puts "result_title:#{r[:format_title]}"
						similar_sorce = similar_sorce(source_title, r[:format_title])
						next if similar_sorce < MAX_SIMILAR
						next if very_different_price(item["price"].to_i, r[:price].to_i)
						
						@remarks += "total_hits:#{s.total_hits} - score:#{r[:score]}\n"
						@remarks += "similar_sorce:#{similar_sorce};\n"
						
						check_props = parse_props(r[:props])
						
						prop_rate = compare_props(r[:cat1_name], source_props, check_props)
						next if prop_rate >= PROP_SORCE
						@remarks += "prop_rate:#{prop_rate}\n"
						
						
						puts "total hits:#{s.total_hits} - id:#{r[:id]} - score:#{r[:score]} - title:#{r[:format_title]} - prop_rate:#{prop_rate}"
						
						#-------结果处理-------------
						#标识该id为delete
						del_item(repeat_item_id)
						#添加至matchs表
						add_match_line(item_id, source_title, repeat_item_id, r[:format_title])
						
					end
					#更新处理状态
					update_max_id(COUTER_ID, item_id)
					puts
					
				end #~ end fetch_data
			end #~ end all items
		end #~ end function
		
		def fetch_data()
			return @tao_db_help.query("select id, iid, nick, cat1_id, cat1_name, detail_url, title, format_title, props_str, price from tao_items where id > #{deal_max_id()} and status = 1  order by id limit #{STEP_LENGTH}")
		end
		
		def get_item_count()
			return @tao_db_help.query("select count(id) from tao_items where id > #{deal_max_id()}").fetch_row()[0].to_i
		end
		
		#当前处理的最大的ID
		def deal_max_id
			#debugger
			return @tao_db_help.query("select max_id from tao_counter where counter_id = 2 ").fetch_row()[0].to_i
		end
		
		#从属性中解释品牌
		def get_brand(props_str)
			return "" if props_str.nil?
			
			brand_name = ""
			
			item_props = props_str.split(";")
			item_props.each do |prop|
				props = prop.split(":")
				next unless props[0].include? "品牌"
				brand_name = props[1]
			end
			brand_name
		end
		
		#通过字符的编辑距离比较是否相似
		def similar_sorce(src1, src2)
			src1, src2 = src1.gsub(" ", ""), src2.gsub(" ", "")
			#puts "#{src1} - #{src2}"
			return src1.pair_distance_similar(src2)
		end
		
		def compare_props(cat_name, source, check)
			rate = 0.0
			#debugger
			@remarks += "compare_props:\n"
			if @prop_config[cat_name.downcase].nil?
				@remarks += "不存在该类别"
				return 0.0 
			end
			
			@prop_config[cat_name.downcase].each do |k, v|
				k = k.downcase
				next if source[k].nil? && check[k].nil? 
				
				if source[k].nil? || check[k].nil? 
					rate += v.to_f / 2
				elsif source[k].downcase.to_s != check[k].downcase.to_s
					@remarks += "  source:#{k} - #{source[k]}\n"
					@remarks += "  check:#{k} - #{check[k]}\n\n"
					
					rate += v.to_f
				end

			end
			rate
		end
		
		def parse_props(props_str)
			return "" if props_str.nil?
			ret = {}
			item_props = props_str.split(";")
			item_props.each do |prop|
				props = prop.split(":")
				ret[props[0]] = props[1]
			end
			ret
		end
		
		def del_item(item_id)
			@tao_db_help.query("update tao_items set status = -2 where id = #{item_id}")
		end
		
		def add_match_line(item_id, tao_item_title, repeat_item_id, repeat_item_title)
			return if has_match(item_id, repeat_item_id)
			
			@tao_db_help.query("insert into tao_item_matchs (tao_item_id, tao_item_title, repeat_item_id, repeat_item_title, status, remarks) values (#{item_id}, '#{@tao_db_help.escape(tao_item_title)}', #{repeat_item_id}, '#{@tao_db_help.escape(repeat_item_title)}', 0, '#{@remarks}')")
		end
		
		def update_max_id(counter_id, max_id)
			@tao_db_help.query("update tao_counter set max_id = #{max_id} where counter_id = #{counter_id}")			
		end
		
		def has_match(item_id, repeat_item_id)
		  #debugger
			@tao_db_help.query("select count(*) from tao_item_matchs where repeat_item_id=#{item_id} and tao_item_id = #{repeat_item_id}").fetch_row()[0].to_i > 0
		end
		
		def very_different_price(source_price, repeat_price)
			ret = false
			if source_price < 50
				ret = true if (repeat_price - source_price).abs > 20
			elsif 50 <= source_price and source_price < 100
				ret = true if (repeat_price - source_price).abs > 30
			elsif 200 > source_price and source_price >= 100
				ret = true if (repeat_price - source_price).abs > 40
			elsif source_price >= 200	
				ret = true if (repeat_price - source_price).abs > 50
			end
			ret
		end
		
	end
end

match = Match::Matcher.new
match.analyzer
